use askama::Template;
use axum::{extract::Query, response::IntoResponse};
use tower_cookies::Cookies;

use crate::{
    config::AppContext,
    domain::{reply::Reply, topic::Topic},
    service::topic_service,
    CommParam, TemplateResponse,
};

use super::base::{base, BaseData};
use crate::template::filters;

#[derive(Template)]
#[template(path = "topic.html")]
pub struct TopicTemplate {
    topic: Topic,
    reply: Vec<Reply>,
    //回复id,页面刷新重新定位用的
    rid: Option<u64>,
    pre: Option<Topic>,
    next: Option<Topic>,
    username: Option<String>,
    base: BaseData,
}
pub async fn index(cookies: Cookies, param: Query<CommParam>) -> impl IntoResponse {
    let param = param.0;
    let id = param.id.unwrap();
    let executor = AppContext::rbatis();
    let topic = topic_service::select_by_id(id).await;
    let reply = Reply::select_by_column(executor, "cid", id).await.unwrap();
    let next = Topic::select_cmp_latest(executor, id, true)
        .await
        .map_or(None, |f| f.first().map_or(None, |f| Some(f.to_owned())));

    let pre = Topic::select_cmp_latest(executor, id, false)
        .await
        .map_or(None, |f| f.first().map_or(None, |f| Some(f.to_owned())));
    let username = cookies
        .get("username")
        .map_or(None, |f| Some(f.value().to_string()));
    let template = TopicTemplate {
        topic,
        reply,
        rid: param.rid,
        username,
        pre,
        next,
        base: base(cookies).await,
    };
    TemplateResponse(template)
}
